import logging
import os
import json
from logging.handlers import RotatingFileHandler
from threading import Lock
import requests


g_lock = Lock()
g_net = requests.Session()


def init_log():
    handler = RotatingFileHandler("./log/log.txt", maxBytes=10240, backupCount=5)
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')

    logger = logging.getLogger("auto")
    logger.addHandler(handler)


def log(e):
    try:
        with g_lock:
            logger = logging.getLogger("auto")
            logger.info(e)
    except Exception:
        pass


def send(url, data):
    ret = g_net.post(url, json=data, headers={'Content-Type': 'aplication/json'})
    return ret.json()


def get_file():
    return "./up.json"


def read_cfg():
    p = get_file()

    if not os.path.exists(p):
        return None

    with open(p, 'r') as f:
        ret = json.load(f)
        return ret

    return None


def write_cfg(d):
    with open(get_file(), 'w') as f:
        json.dump(d, f)
